#include "mainwindow.h"
#include "ui_BuyAndDownloadExample.h"
#include "buycatalog.h"

#include <QtGui/QPushButton>
#include <QtGui/QLabel>
#include <QtGui/QMessageBox>
#include <QtCore/QDirIterator>
#include <QtCore/QDebug>
#include <QtGui/QApplication>
#include <QTimer>
#include <QProgressDialog>

#define KUnlockedContentPath "purchases"

/*
 *
 */
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    catalog = new BuyCatalog(this);
    connect(ui->exitButton, SIGNAL(clicked()), this, SLOT(mainWindowClose()));
    connect(ui->resetButton, SIGNAL(clicked()), this, SLOT(mainWindowResetPurchases()));
    connect(ui->goStoreButton, SIGNAL(clicked()), this, SLOT(mainWindowGotoStore()));
}

MainWindow::~MainWindow()
{
    delete catalog;
    delete ui;
}

void MainWindow::playLevel()
{
    // which button triggered this action and what is the content of the corresponding label (file name)
    QObject* object ;
    QString levelName;
    foreach(object, sender()->parent()->children())
    {
        if(QString::compare(object->metaObject()->className(),"QLabel",Qt::CaseSensitive) == 0)
        {
            levelName = ((QLabel*)object)->text();
            break;
        }
    }

    // find the full path for that file name
    QStringList list = purchasedContent.filter(levelName, Qt::CaseSensitive);
    if(list.count()>0)
    {
        QFile file(list[0]);
        if(file.open(QIODevice::ReadOnly)) {
            QTextStream in(&file);

            QString buffer;
            while(!in.atEnd()) {
                buffer.append(in.readLine());
            }

            //TODO : dear developer, implement text viewer here :)
            QMessageBox msgBox;
            msgBox.setText(buffer);
            msgBox.exec();
        }else{
            QMessageBox::information(0, "error", file.errorString());
        }

        file.close();
    }
}

void MainWindow::listPurchases()
{
    ui->listWidget->clear();
    purchasedContent.clear();

    QStringList filters;
    filters << "*";

    QDirIterator dirit(getPurchaseDir(), filters, QDir::NoFilter, QDirIterator::Subdirectories);
    while(dirit.hasNext())
        purchasedContent.append(dirit.next());

    for (int i = 0; i<purchasedContent.count(); i++)
    {
        QString fileName = purchasedContent.at(i);

        QStringList pathItems = fileName.split("/",QString::SkipEmptyParts,Qt::CaseInsensitive);

        QListWidgetItem *item = new QListWidgetItem();
        ui->listWidget->addItem(item);
        QPushButton *button = new QPushButton();
        button->setText("Read");
        button->setStyleSheet(QString::fromUtf8("QPushButton{ background-color: rgb(0, 0, 255); border-style: outset; border-width: 2px; border-radius: 10px; border-color: beige; font: bold 14px; min-width: 4em; max-width: 5em; padding: 6px; } QPushButton:pressed { background-color: rgb(100, 100, 250); border-style: inset;}"));

        qDebug() << "File " << fileName << "is set as" << button->text() << ".";

        QLabel *label = new QLabel(pathItems.last());
        QHBoxLayout *layout= new QHBoxLayout();
        layout->addWidget(label);
        layout->addWidget(button);
        QWidget *widget = new QWidget();
        widget->setLayout(layout);
        item->setSizeHint(widget->sizeHint());
        ui->listWidget->setItemWidget(item, widget);

        connect(button, SIGNAL(clicked()), this, SLOT(playLevel()));
    }
}

QPushButton *MainWindow::getButton(QString& fname)
{
    for(int i = 0; i < ui->listWidget->count(); i++)
    {
        QListWidgetItem* item = ui->listWidget->item(i);
        QWidget* widget = ui->listWidget->itemWidget(item);
        foreach(QObject* object, widget->children())
        {
            QWidget *child = qobject_cast<QWidget*>(object);
            if(!child)
                continue;

            if(QString::compare(child->whatsThis(), fname) == 0)
            {
                return qobject_cast<QPushButton*>(object);
            }
        }
    }
    return NULL;
}

/*
 *
 */
void MainWindow::catalogClosed()
{
    listPurchases();
}

void MainWindow::mainWindowClose()
{
    close();
}

void MainWindow::mainWindowResetPurchases()
{
    QString dirName = getPurchaseDir();
    QDir dir(dirName);

    if(!dir.exists(dirName))
        return;

    bool result;
    foreach(QFileInfo info, dir.entryInfoList(QDir::NoDotAndDotDot |
                                              QDir::System |
                                              QDir::Hidden  |
                                              QDir::AllDirs |
                                              QDir::Files,
                                              QDir::DirsFirst))
    {
        result = QFile::remove(info.absoluteFilePath());
        if (!result)
        {
            break;
        }
    }
    dir.rmdir(dirName);
    listPurchases();
}

void MainWindow::mainWindowGotoStore()
{
    catalog->showFullScreen();
}

QString MainWindow::getPurchaseUri(const QString& productID)
{
    QString fname(getPurchaseDir());
    fname.append("/");
    fname.append(productID);
    fname.append(".book");
    return fname;
}

QString MainWindow::getPurchaseDir()
{
    QString fname(QApplication::applicationDirPath());
    fname.append("/");
    fname.append(KUnlockedContentPath);
    return fname;
}

